package com.lb.shopguide.manager.receiver;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioAttributes;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;

import com.blankj.utilcode.util.LogUtils;
import com.lb.shopguide.GuideApplication;
import com.lb.shopguide.R;
import com.lb.shopguide.config.UserConfigManager;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.ui.activity.BossMainActivity;
import com.lb.shopguide.ui.activity.GuideMainActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;

import cn.jpush.android.api.JPushInterface;

/**
 * 自定义接收器
 * <p>
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class PushReceiver extends BroadcastReceiver {
    private static final String TAG = "JPush";

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        Intent localIntent = new Intent();
        LogUtils.d(TAG, "[PushReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));
        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            LogUtils.d(TAG, "[PushReceiver] 接收Registration Id : " + regId);
            //send the Registration Id to your server...
        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            LogUtils.d(TAG, "[PushReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
//            LogUtils.d(TAG, "[PushReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
            String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
            if (AppConstant.BROADCAST_PAID.equals(message)) {//邀请
                localIntent.setAction(AppConstant.BROADCAST_PAID);
                localIntent.putExtras(bundle);
                sendBroad(context, localIntent);
            } else if (AppConstant.BROADCAST_FAIL.equals(message)) {
                localIntent.setAction(AppConstant.BROADCAST_FAIL);
                localIntent.putExtras(bundle);
                sendBroad(context, localIntent);
            } else if (AppConstant.BROADCAST_ROB.equals(message)) {
                localIntent.setAction(AppConstant.BROADCAST_ROB);
                localIntent.putExtras(bundle);
                sendBroad(context, localIntent);
            } else if (AppConstant.BROADCAST_ESOTERICA.equals(message)) {
                localIntent.setAction(AppConstant.BROADCAST_ESOTERICA);
                localIntent.putExtras(bundle);
                sendBroad(context, localIntent);
            } else if (AppConstant.BROADCAST_RECOMMEND.equals(message)) {
                localIntent.setAction(AppConstant.BROADCAST_RECOMMEND);
                localIntent.putExtras(bundle);
                sendBroad(context, localIntent);
            } else if (AppConstant.BROADCAST_UPDATE.equals(message)) {
                localIntent.setAction(AppConstant.BROADCAST_UPDATE);
                localIntent.putExtras(bundle);
                sendBroad(context, localIntent);
            } else if (AppConstant.BROADCAST_LOGIN.equals(message)) {
//                localIntent.setAction(AppConstant.BROADCAST_LOGIN);
//                localIntent.putExtras(bundle);
//                sendBroad(context, localIntent);
            } else if (AppConstant.BROADCAST_CHANGE_STAFF.equals(message)) {
                localIntent.setAction(AppConstant.BROADCAST_CHANGE_STAFF);
                localIntent.putExtras(bundle);
                sendBroad(context, localIntent);
            } else if (AppConstant.BROADCAST_BIND_STAFF.equals(message)) {
                localIntent.setAction(AppConstant.BROADCAST_BIND_STAFF);
                localIntent.putExtras(bundle);
            } else if (AppConstant.BROADCAST_STAFF_DIVIDE.equals(message)) {
                localIntent.setAction(AppConstant.BROADCAST_STAFF_DIVIDE);
                localIntent.putExtras(bundle);
                sendBroad(context, localIntent);
            } else if (AppConstant.BROADCAST_WAP_QRPAY.equals(message)) {
                localIntent.setAction(AppConstant.BROADCAST_WAP_QRPAY);
                localIntent.putExtras(bundle);
                sendBroad(context, localIntent);
            } else if (AppConstant.BROADCAST_FANS_NEW.equals(message)) {//新增粉丝
                localIntent.setAction(AppConstant.BROADCAST_FANS_NEW);
                localIntent.putExtras(bundle);
                sendBroad(context, localIntent);
            } else if (AppConstant.BROADCAST_FANS_CHANGE.equals(message)) {//粉丝变会员
                localIntent.setAction(AppConstant.BROADCAST_FANS_CHANGE);
                localIntent.putExtras(bundle);
                sendBroad(context, localIntent);
            } else if (AppConstant.BROADCAST_ACTIVITY_FINISH.equals(message)) {
                localIntent.setAction(AppConstant.BROADCAST_ACTIVITY_FINISH);
                localIntent.putExtras(bundle);
                sendBroad(context, localIntent);
            }
        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            if (bundle.containsKey(JPushInterface.EXTRA_ALERT)) {
                String activity = "";
                String bossInfo = "";
                String info = bundle.getString(JPushInterface.EXTRA_EXTRA);
                if (info.contains("jumpMode")) {//就说明 这个是8.30相关的推送
                    showNotificationRec(context, bundle);
                    return;
                }
                try {
                    JSONObject jsonObject = new JSONObject(info);
                    if (jsonObject.has("activity")) {
                        activity = jsonObject.getString("activity");
                    }
                    if (jsonObject.has("boss")) {
                        bossInfo = jsonObject.getString("boss");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //{"boss":"BOSS_ASSISTANT"}
                if (UserConfigManager.getInstance(context).isPushMessage()) {
                    if (activity.equals(AppConstant.ACTIVITY_BILLION_ACTIVITY)
                            || activity.equals(AppConstant.ACTIVITY_LUCK_ACTIVITY)) {
                        showNotificationMember(context, bundle);
                    }
                    if (bossInfo.equals(AppConstant.ACTIVITY_BOSS_MESSAGE)) {
                        showNotificationBoss(context, bundle);
                        localIntent.setAction(AppConstant.BROADCAST_BOSS_SECRETARY);
                        localIntent.putExtras(bundle);
                        sendBroad(context, localIntent);
                    }
                }
            }
        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
//            PushInfo info = JsonUtil.getGson().fromJson(bundle.getString(JPushInterface.EXTRA_EXTRA), PushInfo.class);
//            pushToMain(context, info);
        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
            LogUtils.d(TAG, "[PushReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
            //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..

        } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
            boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
            LogUtils.w(TAG, "[PushReceiver]" + intent.getAction() + " connected state change to " + connected);
        } else {
            LogUtils.d(TAG, "[PushReceiver] Unhandled intent - " + intent.getAction());
        }
    }

    private void sendBroad(Context context, Intent intent) {
        context.sendBroadcast(intent);
    }

    private void showNotificationMember(Context context, Bundle bundle) {
        Bundle targetBundle = new Bundle();
        targetBundle.putInt(AppConstant.NOTIFICATION_TARGET, AppConstant.NOTIFICATION_TARGET_MEMBER);
        Intent targetIntent = new Intent(context, GuideMainActivity.class);
        targetIntent.putExtras(targetBundle);
        prepareNotification(context, bundle, targetIntent);
    }

    private void showNotificationRec(Context context, Bundle bundle) {//8:30
        Bundle targetBundle = new Bundle();
        targetBundle.putInt(AppConstant.NOTIFICATION_TARGET, AppConstant.NOTIFICATION_TARGET_REC);
        targetBundle.putString(AppConstant.NOTIFICATION_INFO, bundle.getString(JPushInterface.EXTRA_EXTRA));
        Intent targetIntent = new Intent(context, GuideMainActivity.class);
        targetIntent.putExtras(targetBundle);
        prepareNotification(context, bundle, targetIntent);
    }

    private void showNotificationBoss(Context context, Bundle bundle) {
        Bundle targetBundle = new Bundle();
        targetBundle.putInt(AppConstant.NOTIFICATION_TARGET, AppConstant.NOTIFICATION_TARGET_SECRETARY);
        Intent targetIntent = new Intent(context, BossMainActivity.class);
        targetIntent.putExtras(targetBundle);

        prepareNotification(context, bundle, targetIntent);
    }

    private void prepareNotification(Context context, Bundle bundle, Intent targetIntent) {
        int notificationId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, AppConstant.CHANNEL_BOSS_NOTIFICATION);
        mBuilder.setContentTitle(bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE))//设置通知栏标题
                .setContentText(bundle.getString(JPushInterface.EXTRA_ALERT)) //设置通知栏显示内容
                .setContentIntent(PendingIntent.getActivity(context, 1, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT)) //设置通知栏点击意图
//  .setNumber(number) //设置通知集合的数量
                .setTicker(JPushInterface.EXTRA_NOTIFICATION_TITLE + "消息")//通知首次出现在通知栏，带上升动画效果的
                .setWhen(System.currentTimeMillis())//通知产生的时间，会在通知信息里显示，一般是系统获取到的时间
                .setPriority(Notification.PRIORITY_DEFAULT) //设置该通知优先级
                .setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消
//.setOngoing(false)//ture，设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
                .setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS)//向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置，使用defaults属性，可以组合
                .setSound(Uri.parse("android.resource://" + GuideApplication.getAppContext().getPackageName() + "/" + R.raw.beep))
                .setSmallIcon(R.drawable.logo);//注：PendingIntent开启新的界面，intent携带值传递的时候，PendingIntent的类型是FLAG_UPDATE_CURRENT，新的值过来，自动更新，intent需要设置Action才可以获得传递的值
        adapterAndroidOreo(mNotificationManager);
        mNotificationManager.notify(notificationId, mBuilder.build());
    }

    /**
     * 适配android8.0
     *
     * @param mNotificationManager
     */
    private void adapterAndroidOreo(NotificationManager mNotificationManager) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(AppConstant.CHANNEL_BOSS_NOTIFICATION, "身边店", NotificationManager.IMPORTANCE_DEFAULT);
            channel.enableVibration(true);
            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
                    .build();
            channel.setSound(Uri.parse("android.resource://" + GuideApplication.getAppContext().getPackageName() + "/" + R.raw.beep), audioAttributes);
            mNotificationManager.createNotificationChannel(channel);
        }
    }

//    private void pushToMain(Context context, PushInfo info) {
//        if (AppUtils.isAppForeground(context)) {
//            if (!TextUtils.isEmpty(UserConfigManager.getInstance(context).getUserToken())) {
//                Intent localIntent = new Intent(context, GuideMainActivity.class);
//                localIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                localIntent.putExtras(getBundle(info));
//                context.startActivity(localIntent);
//            } else {//没有token直接进入guide
//                gotoGuide(context, info);
//            }
//        } else {
//            gotoGuide(context, info);
//        }
//    }


    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:").append(key).append(", value:").append(bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:").append(key).append(", value:").append(bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
                    LogUtils.i(TAG, "This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next().toString();
                        sb.append("\nkey:").append(key).append(", value: [").append(myKey).append(" - ").append(json.optString(myKey)).append("]");
                    }
                } catch (JSONException e) {
                    LogUtils.e(TAG, "Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }

//	private void processCustomMessage(Context context, Bundle bundle) {
//		if (GuideMainActivity.isForeground) {
//			String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
//			String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
//			Intent msgIntent = new Intent(GuideMainActivity.MESSAGE_RECEIVED_ACTION);
//			msgIntent.putExtra(GuideMainActivity.KEY_MESSAGE, message);
//			if (!ExampleUtil.isEmpty(extras)) {
//				try {
//					JSONObject extraJson = new JSONObject(extras);
//					if (extraJson.length() > 0) {
//						msgIntent.putExtra(GuideMainActivity.KEY_EXTRAS, extras);
//					}
//				} catch (JSONException e) {
//
//				}
//
//			}
//			context.sendBroadcast(msgIntent);
//		}
//	}

}
